require(["jquery","bbcare",
        "scprit/department/vm/assessmentScreening/peabodyScale.ui.js",
        "scprit/department/vm/assessmentScreening/assessmentScreeningQuestion.servers.js",
        "scprit/department/vm/assessmentScreening/peabodyScale.event.js"],
    function ($,$bb,$ui,$servers,$event) {
        var getParams = $bb.getPageParams();
        var type = getParams.type;
        var userId = getParams.userId;
        var answerId = getParams.answerId;
        // 如果清除本地医生修改的起始月份
        if (sessionStorage.getItem('peabody_scale_start_month')) {
            sessionStorage.removeItem('peabody_scale_start_month')
        }
        //问卷题目获取：
        var paramsQuestion = $servers.getParams(type,userId);
        var arr1 = [
            {'name':"反射",'id':"reflex"},
            {'name':"姿势",'id':"posture"},
            {'name':"移动",'id':"motion"},
            {'name':"抓握",'id':"grab"},
            {'name':"视觉-运动",'id':"visuomotor"}
        ];
        var arr2 = [
            {'name':"姿势",'id':"posture"},
            {'name':"移动",'id':"motion"},
            {'name':"实物操作",'id':"practice"},
            {'name':"抓握",'id':"grab"},
            {'name':"视觉-运动",'id':"visuomotor"}
        ];
        //患者信息展示：
        var infoParams = $servers.infoParams(userId);

        var infoFn = function(dt, draft){
            $event.userInfo = dt;
            //基本信息渲染：
            dt = dt.data;
            var diff,answerResult;
            if (draft) {
                answerResult = $.parseJSON(draft.result.result);
                diff = $servers.dateDiff(dt.PatientInfo.birthday, draft.result.testTime);
                dt.PatientInfo.testDate = draft.result.testTime;
            } else if (answerId){
                answerResult = $.parseJSON(getParams.answer.answerResult);
                diff = $servers.dateDiff(dt.PatientInfo.birthday,getParams.testTime);
                dt.PatientInfo.testDate = getParams.testTime;
            } else {
                diff = $servers.dateDiff(dt.PatientInfo.birthday,$servers.getNowFormatDate());
                dt.PatientInfo.testDate = $servers.getNowFormatDate();
            }
            var monthAge1 = $servers.getMonthAge(diff,dt.PatientInfo.pregnancyDay);
            dt.PatientInfo.isPremature = monthAge1.flag;
            // dt.PatientInfo.monthAge = monthAge1.monthAge;
            dt.PatientInfo.monthAge = window.getAge(dt.PatientInfo.birthday, new Date(), 280 - dt.PatientInfo.pregnancyDay);
            $ui.basicInfoInit({'id':'#basicInfo','data':dt.PatientInfo});
            //渲染问卷：
            var scoreObj = {'reflex':{},'posture':{},'motion':{},'grab':{},'visuomotor':{},'practice':{},'bottom':{},'top':{}};
            var monthAge = $event.getMonthAge(diff,dt.PatientInfo.pregnancyDay);
            var quesArr = monthAge < 12 ? arr1 : arr2 ;
            var ids = $event.getIds(quesArr);
            if(answerId){$event.tabAttr(quesArr,answerResult);}
            var initTab = quesArr[0];
            $ui.tabInit({"id":"#testSelect","data":quesArr});
            var quesFn = function(data){
                if(!answerId && !draft){
                    var dataInit = $event.quesDeal(monthAge,data.data[initTab.name],initTab.name);
                    $ui.peabodyInit({"id":"#question","data":dataInit.data});
                    $ui.scoreTabInit({"id":"#scores-show","data":dataInit.scoresTab});
                    // begin 自定义起始月龄
                    $("#userDefinedMonth").css({"display":"block"});
                    $("#userDefinedMonth button").unbind("click");
                    $("#userDefinedMonth button").click(function(){
                        var text = $(this).parent().prev().val();
                        var reg = /^[0-9]+$/;
                        if( !reg.test(text) ){
                            $bb.toastShow("请输入数字！",1500);
                        }else{
                            var arrMonthAgeTotal = $event.getMonthAgeTotal(dataInit.data);
                            $("#userDefinedMonth input").val("");
                            if( !$event.getFlagMonthAge(arrMonthAgeTotal,text) ){
                                var str = arrMonthAgeTotal.join("、");
                                $bb.toastShow("请输入年龄范围在"+ str +"月龄之中！");
                            }else{
                                var goingId = $event.getGoingIdByMonth(dataInit.data,text);
                                var dataInit1 = $event.quesDeal(monthAge,data.data[initTab.name],initTab.name,goingId);
                                $ui.peabodyInit({"id":"#question","data":dataInit1.data});
                                $ui.scoreTabInit({"id":"#scores-show","data":dataInit1.scoresTab});
                                $(this).parent().prev().val(text)
                                sessionStorage.setItem('peabody_scale_start_month', text)
                            }
                        }
                    });
                    // end 自定义起始月龄
                    $event.tabClick(monthAge,data.data,scoreObj,ids);
                    $event.topAndBottomInit([]);
                    $event.scoreClick(dataInit.data,scoreObj,'','',ids);
                    $event.submit('PEABODY',userId,scoreObj,"#doctorPost");
                } else if (draft) {
                    var dataInit = $event.quesDeal(monthAge,data.data[initTab.name],initTab.name);
                    $ui.peabodyInit({"id":"#question","data":dataInit.data});
                    $ui.scoreTabInit({"id":"#scores-show","data":dataInit.scoresTab});  
                    $event.showToast = false;
                    var group1 = ['reflex', 'posture', 'motion', 'grab', 'visuomotor'],
                        group2 = ['posture', 'motion', 'practice', 'grab', 'visuomotor'],
                        group = monthAge < 12 ? group1 : group2;
                    var groupIndex = 0;
                    function selectTab(group) {
                        var id = group[groupIndex], arr ;
                        if (!id) return;
                        if (!$.isEmptyObject(answerResult[id])) {
                            $('#' + id).click();
                            arr = Object.keys(answerResult[id]).length;
                        } else {
                            groupIndex++;
                            return selectTab(group);
                        }

                        selectQuestion(function () {
                            groupIndex++
                            if (!$.isEmptyObject(answerResult[id])) {
                                selectTab(group)
                            } else {
                                $event.showToast = true;
                                $event._vm.loading = false;
                            }
                        });

                        function selectQuestion(callback) {
                            var current = $($('.now-item').find('li'))[1].innerText;
                            var val
                            try {
                                val = answerResult[id][current];
                            } catch (err) {}
                            $('.fractional-item[score='+ val +']').mousedown();
                            $('.fractional-item[score='+ val +']').mouseup();
                            arr--;
                            if (arr >= 0) {
                                selectQuestion(callback);
                            } else {
                                callback();
                            }
                        }
                    }

                    setTimeout(function () {
                        selectTab(group);
                    }, 50)

                    $event.tabClick(monthAge,data.data,scoreObj,ids);
                    $event.topAndBottomInit([]);
                    $event.scoreClick(dataInit.data, scoreObj,'','',ids);
                    $event.submit('PEABODY',userId,scoreObj,"#doctorPost");

                } else {
                    $("#doctorPost").val(getParams.business ? getParams.business : "评估医生")
                    var quesType = quesArr[0].id;

                    if($.isEmptyObject(answerResult[quesType])){
                        dataInit = $event.quesDeal(monthAge,data.data[initTab.name],initTab.name);
                        $ui.peabodyInit({"id":"#question","data":dataInit.data});
                        $ui.scoreTabInit({"id":"#scores-show","data":dataInit.scoresTab});
                    } else{
                        var dataInit2 = $event.quesRecord(data.data,initTab.name,answerResult);
                        $ui.peabodyInit({"id":"#question","data":dataInit2.data[initTab.name]});
                        var id = "#"+quesType+"-"+dataInit2.minId;
                        $event.scoreInit(id);
                    }

                    $event.topAndBottomInit(answerResult,initTab.name);
                    $event.tabClick2(monthAge,data.data,answerResult, draft);
                    $event.quesClick();
                }
            };
            $servers.getQuestion(paramsQuestion,quesFn);
        };

        $servers.getInfo(infoParams,infoFn);

        $event.refresh = function () {
            $servers.getInfo(infoParams,infoFn);
        }

        $event.initVm(infoFn);
    });